package main

import (
	"bufio"
	"fmt"
	"github.com/sirupsen/logrus"
	"log"
	"os"
	"strings"
)

func main() {
	// 获取当前项目路径
	currentDir, err := os.Getwd()
	logFilePath := currentDir + "/user-745766f4f8-rvchn.log"
	level := logrus.InfoLevel

	filteredLogs, err := filterLogsByLevel(logFilePath, level)
	if err != nil {
		fmt.Printf("过滤日志时出错: %v\n", err)
		return
	}

	fmt.Printf("过滤后的日志:\n")
	log.Println(filteredLogs)
}
func parseLogLevel(line string) logrus.Level {
	if strings.Contains(line, "debug") {
		return logrus.DebugLevel
	}
	if strings.Contains(line, "info") {
		return logrus.InfoLevel
	}
	if strings.Contains(line, "warn") {
		return logrus.WarnLevel
	}
	if strings.Contains(line, "error") {
		return logrus.ErrorLevel
	}
	return logrus.InfoLevel // 默认返回 info 级别
}

// filterLogs 过滤指定级别的日志
func filterLogsByLevel(filePath string, level logrus.Level) ([]string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, fmt.Errorf("打开文件时出错: %v", err)
	}
	defer file.Close()

	var filteredLogs []string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if parseLogLevel(line) == level {
			filteredLogs = append(filteredLogs, line)
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("读取文件时出错: %v", err)
	}

	return filteredLogs, nil
}
